/*
 * Copyright (C) 2020 Agrui
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdlib.h>
#include <string.h>
#include <MessageType.h>
#include <MessagePool.h>

static MessagePool* sPool = NULL;


void messagePoolInit() {
    if (!sPool) {
        sPool = (MessagePool*)malloc(sizeof(MessagePool));
        if (!sPool) {
            return;
        }

        memset(sPool, 0, sizeof(MessagePool));

        sPool->mLock = newLock();
        if (!sPool->mLock) {
            free(sPool);
            sPool = NULL;
            return;
        }
    }
}

void messagePoolDeInit() {
    if (sPool) {
        Message* n;
        Message* p;
        lock(sPool->mLock);
        p= sPool->mPool;
        while (p != NULL) {
            n = p->next;
            free(p);
            p = n;
        }
        unlock(sPool->mLock);
        if (sPool->mLock) {
            deleteLock(sPool->mLock);
        }

        free(sPool);
        sPool = NULL;
    }
}

Message* messagePoolObtain() {
    Message* m = NULL;

    if (!sPool || !sPool->mLock) {
        return NULL;
    }

    lock(sPool->mLock);
    if (sPool->mPoolSize < MAX_POOL_SIZE) {
        if (sPool->mPool) {
            m = sPool->mPool;
            sPool->mPool = m->next;
            m->next = NULL;
            sPool->mPoolSize--;
        }
    }
    unlock(sPool->mLock);
    return m;

}

void messagePoolAdd(Message* msg) {

    if (!sPool || !sPool->mLock || !msg) {
        return;
    }

    lock(sPool->mLock);
    if (sPool->mPoolSize < MAX_POOL_SIZE) {
        msg->next = sPool->mPool;
        sPool->mPool = msg;
        sPool->mPoolSize++;
    } else {
        free(msg);
    }
    unlock(sPool->mLock);
}

